import { defineStore } from 'pinia';
import { logout, getInfo } from '@/request/login';
import storage from '@/utils/storage';
import { stringify } from 'querystring';
export const userStore = defineStore({
    id: 'user', // id必填，且需要唯一
    state: () => {
        return {
            token: '',
            userInfo: {},
            isCollapse: false,
            roles: [],
            permissions: [],
            permisaction: [],
            userId: '',
        };
    },
    actions: {
        setNavIsCollapse() {
            this.isCollapse = !this.isCollapse;
        },
        setToken(str: string) {
            this.token = str;
        },
        // get user info
        getInfos() {
            getInfo()
                .then((response: any) => {
                    if (!response || !response.data) {
                        this.token = '';
                        storage.remove('token');
                    }
                    const { roles, permissions, userId } = response.data;
                    this.userInfo = response.data;
                    const obj = {
                        OperId: response.data.userId,
                        OperName: response.data.userName,
                        OperType: response.data.roles.toString(),
                    };
                    storage.set('user', JSON.stringify(obj));
                    this.roles = roles;
                    this.permisaction = permissions;
                    this.userId = userId;
                })
                .catch(() => {
                    this.userInfo = {};
                });
        },
        // 退出系统
        LogOut() {
            logout()
                .then((res) => {
                    if (res.code == 200) {
                        this.token = '';
                        storage.clear();
                        sessionStorage.clear();
                    }
                })
                .catch(() => {
                    this.userInfo = {};
                });
        },
    },
});
